package com.baichuan.zntx.rules;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baichuan.common.core.utils.DateUtils;
import com.baichuan.zntx.domain.Device;
import com.baichuan.zntx.domain.Task;
import com.baichuan.zntx.domain.bo.MessageBo;
import com.baichuan.zntx.domain.vo.MessageVo;
import com.baichuan.zntx.service.IMessageService;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @author mazhanliang
 */
@Rule(name = "Timeout Rule", description = "Triggers when the task exceeds the specified timeout threshold")
public class TimeoutRule {
    private Device device;
    private final IMessageService messageService;

    public TimeoutRule(IMessageService messageService) {
        this.messageService = messageService;
    }

    @Condition
    public boolean isTaskTimeout(Facts facts) {
        device = facts.get("device");
        Task task = facts.get("task");
        LocalDateTime now;
        if(task.getStatus()!=2){
            // 获取任务开始时间
            now = LocalDateTime.now();
        }else{
            now = task.getExcuteTime();
        }

        long execDur = LocalDateTimeUtil.between(task.getStartTime(), now, ChronoUnit.MINUTES);
        return execDur > device.getTaskDuration();
    }

    @Action
    public void triggerTimeoutAlarm() {
        MessageBo messageBo = new MessageBo();
        messageBo.setStatus(-1);
        messageBo.setDeviceId(device.getId());
        messageBo.setType(1);
        List<MessageVo> messageVoList = messageService.queryList(messageBo);
        if(messageVoList==null || messageVoList.isEmpty()){
            messageBo.setContent("任务超时报警:" + device.getDeviceId());
            messageBo.setSendTime(DateUtils.getNowDate());
            messageBo.setSendCount(0);
            messageService.insertByBo(messageBo);
        }

    }
}

